package com.net.oil.app;

import com.google.gson.Gson;
import com.net.oil.user.bean.UserInfo;
import com.net.oil.util.SharedPreferencesKey;
import com.net.oil.util.SharedPreferencesUtil;
import com.net.oil.util.StringUtil;

/**
 * 作者：lch
 * 时间：2018/3/31:15:37
 * 邮箱：245850413@qq.com
 * 说明：用户信息管理类
 */

public class UserInfoManager {

    private static UserInfoManager instance;
    private UserInfo userInfo;
    private UserInfo.TokenBean tokenBean;

    private UserInfoManager(){}

    public static UserInfoManager getInstance() {

        if (instance == null) {
            synchronized (UserInfoManager.class) {
                if (instance == null) {
                    instance = new UserInfoManager();
                }
            }
        }
        return instance;
    }

    /**
     * 获取用户信息
     * @return  userInfo
     */
    public UserInfo getUserInfo(){
        if (userInfo == null){
            String userInfoJson = SharedPreferencesUtil.getStringParam(MyApp.getApplication().getApplicationContext(), SharedPreferencesKey.USER_INFO, "");
            if (!StringUtil.isEmpty(userInfoJson)){
                Gson gson = new Gson();
                userInfo =  gson.fromJson(userInfoJson, UserInfo.class);
            }else {
                return null;
            }
        }
        return userInfo;
    }

    /**
     * 保存用户信息
     * @param userInfoJson  用户信息
     */
    public void setUserInfo(String userInfoJson){
        Gson gson = new Gson();
        userInfo = gson.fromJson(userInfoJson, UserInfo.class);
        tokenBean = userInfo.getToken();
        SharedPreferencesUtil.setStringParam(MyApp.getApplication().getApplicationContext(), SharedPreferencesKey.USER_INFO, userInfoJson);
    }

    /**
     * 获取token
     * @return  token
     */
    public String getToken(){
        userInfo = getUserInfo();
        if (userInfo != null){
            if (userInfo.getToken() != null){
                return userInfo.getToken().getRealToken();
            }
        }
        return "";
    }

    /**
     * 清除用户信息
     */
    public void clearUserInfo(){
        userInfo = null;
        SharedPreferencesUtil.setStringParam(MyApp.getApplication().getApplicationContext(), SharedPreferencesKey.USER_INFO, "");
    }

    /**
     * 判断用户是否登陆
     * @return  true 登陆，false 未登录
     */
    public boolean isLogin(){
        return getUserInfo() != null && !StringUtil.isEmpty(getToken());
    }
}
